<template>
  <div>
    <el-card
      style="width: 600px; height: 100px"
      shadow="always"
      v-for="(item, index) in todolist"
      :key="item.id"
      class="box"
    >
      <span>{{ item.title }}</span>
      <span> {{ item.content }}</span>
      <span>
        是否公开
        <el-switch
          v-model="item.status"
          class="ml-2"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
      /></span>

      <el-button type="success" size="small" @click="edit(item)"
        >编辑</el-button
      >
      <el-button type="warning" size="small" @click="del(item.id)"
        >删除</el-button
      >
    </el-card>

    <el-dialog v-model="centerDialogVisible" title="编辑" width="500" center>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="editlist"
        status-icon
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="文章标题" prop="pass">
          <el-input v-model="editlist.title" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="内容" prop="checkPass">
          <el-input v-model="editlist.content" type="text" autocomplete="off" />
        </el-form-item>
        是否公开
        <el-switch
          v-model="editlist.status"
          class="ml-2"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="finedit()">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import http from "../utils/http";
import { ref } from "vue";

let todolist = ref([]);
let editlist = ref([]);
const centerDialogVisible = ref(false);
async function loadlist() {
  let r = await http({
    url: "/posts",
  });
  console.log(r);
  todolist.value = r.data;
}
loadlist();
async function del(id) {
  console.log(id);
  let r = await http({
    url: "/posts/" + id,
    method: "delete",
  });
  console.log(r.data);
  loadlist();
}

async function edit(item) {
  editlist.value = JSON.parse(JSON.stringify(item));
  console.log(editlist.value);
  centerDialogVisible.value = true;
}
async function finedit() {
    let r = await http({
        url: '/posts/' + editlist.value.id,
        method: 'patch',
        data: editlist.value
    });
    console.log(r.data);
    loadlist();
    centerDialogVisible.value = false;
}
</script>
<style scoped>
.box {
  display: flex;
  justify-content: space-around;
}
</style>
